package com.bdqn.t362.user.servlet;

import com.aliyuncs.utils.StringUtils;
import com.bdqn.t362.common.utils.OSSUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

/**
 * @author lqm
 * @ClassName ${UploadOSSServlet}
 * @description: 上传文件到阿里云OSS
 */
@WebServlet("/UploadOSSServlet")
public class UploadOSSServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String imgSrc = "";
        String loadResult = "";
        try {
            //获取表单提交的文件流
            Part part = request.getPart("userImg");


            //tomcat 8之前获取文件名的方法需要获取文件名
//        String contentDis = part.getHeader("content-disposition");
//        System.out.println("contentDis=" + contentDis);
//        String[] contentArr = contentDis.split(";");
//        String fileName = "";
//        for (String tempStr : contentArr) {
//            //filename="AA83389CA26D89BCB4E50524347E18CF.png"
//            if (tempStr.trim().startsWith("filename")) {
//                fileName = tempStr.substring(tempStr.indexOf("=") + 2, tempStr.length() - 1);
//            }
//        }

            //存储到本地 该方法tomcat8之后才可用
            String fileName = part.getSubmittedFileName();
            //给上传文件一个新的名字
            String newFileName = UUID.randomUUID().toString();
            //获取文件后缀
            String prefix = fileName.substring(fileName.lastIndexOf("."));

            imgSrc = newFileName + prefix;

            loadResult = OSSUtil.uploadInStream(part.getInputStream(), newFileName + prefix);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        //如果为空则上传OSS失败
        if (!StringUtils.isEmpty(loadResult)) {
            request.setAttribute("imgSrc", imgSrc);
        } else {
            request.setAttribute("errorMsg", "上传文件失败！");
        }
        request.getRequestDispatcher("index.jsp").forward(request, response);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
